// 创建一个webview的react-native组件页面
import React, {useState, useEffect} from 'react';
import {View, StyleSheet, ActivityIndicator} from 'react-native';
import {WebView} from 'react-native-webview';
import {useRoute} from '@react-navigation/native';
import {getLogger} from '@siteed/react-native-logger';

import qs from 'qs';
import {get, post} from '../http/http';
import {useDispatch} from 'react-redux';
import {loginInnerTeacher} from '../store/rootSlice';
const logger = getLogger('App');
const WebviewPage = ({navigation, route}) => {
  const dispatch = useDispatch();

  console.log(route);
  const url =
    route.params && route.params.url
      ? route.params.url
      : 'http://172.22.181.69/h5/#/pages/authorizeLogin';
  const [loading, setLoading] = useState(true);
  const handleNavigationStateChange = navState => {
    console.log(navState);
    if (navState.url) {
      // 从navState的url中取query参数
      const params = qs.parse(navState.url.split('?')[1]);

      console.log('params:', params);
      console.log('url--->', navState.url);
      logger.info('url:', JSON.stringify(navState));
      logger.info('params:', JSON.stringify(params));
      if (
        navState.url.indexOf('http://172.22.181.69/h5/') >= 0 &&
        navState.url.indexOf('uid=') >= 0
      ) {
        const uid = params.uid.split('#')[0];
        dispatch(
          loginInnerTeacher(uid, () => {
            navigation.goBack();
          }),
        );
      }
    }
  };
  return (
    <View style={styles.container}>
      {loading && (
        <ActivityIndicator
          size="large"
          color="#FF3333"
          style={styles.loadingIndicator}
        />
      )}
      <WebView
        source={{uri: url}}
        onLoadEnd={() => setLoading(false)}
        style={styles.webview}
        onNavigationStateChange={handleNavigationStateChange}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  loadingIndicator: {
    position: 'absolute',
    top: '50%',
    left: '50%',
    transform: [{translateX: -25}, {translateY: -25}],
  },
  webview: {
    flex: 1,
  },
});

export default WebviewPage;
